import mongoose from 'mongoose'
const Movie = mongoose.model('Movie')

export const getAllMovies = async (type, year, pageSize, pageNum) => {
  let query = {}
  if (type) {
    query.movieTypes = {
      $in: [type]
    }
  }
  if (year) {
    query.year = year
  }
  let movies = await Movie.find(query)
  const count = await Movie.find({}).count()
  return { movies, count }
}

export const getMoviesList = async (pageSize, pageNum) => {
  let movies
  if (!!pageSize && !!pageNum) {
    movies = await Movie.find({}).skip((pageNum - 1) * pageSize).limit(Number(pageSize))
  }
  const count = await Movie.find({}).count()
  return { movies, count }
}

export const getSingleMovie = async (id) => {
  const movie = await Movie.findOne({
    _id: id
  }, (err, docs) => {
      // docs.forEach
    if (err) {
      return {}
    }
  })

  return movie
}

export const getRelativeMovies = async (movie) => {
  const relativeMovies = await Movie.find({
    movieTypes: {
      $in: movie.movieTypes
    }
  })

  return relativeMovies
}

export const deleteMovie = async (_id) => {
  const deleteMovie = await Movie.deleteOne({
    _id
  })

  return deleteMovie
}
